/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.validation.client.constraints;

import com.cleangwt.json.client.StringDeserializer;
import com.cleangwt.validation.client.DeferredValidation;
import com.cleangwt.web.client.PendingCallback;
import com.cleangwt.web.client.Requests;

/**
 * A {@link DeferredValidation} to invoke remote service for validating.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class RemoteValidation extends DeferredValidation {
  private final String message;
  private final String url;

  /**
   * Creates a remote validator with the given url, message and default group.
   * 
   * @param url the url of remote service
   * @param message the error message
   */
  public RemoteValidation(String url, String message) {
    this(url, message, (String[]) null);
  }

  /**
   * Creates a remote validator with the given url, message and groups.
   * 
   * @param url the url of remote service
   * @param message the error message
   * @param groups the groups
   */
  public RemoteValidation(String url, String message, String... groups) {
    super(groups);
    // assert message != null;
    this.url = url;
    this.message = message;
  }

  @Override
  protected void validateDeffered(Object value) {
    Requests.postObject(url, value, new PendingCallback(errorReporter.createPendingHandler()) {
      //
      // @Override
      // public void onError(Request request, Throwable exception)
      // {
      // errorReporter.reportErrorMessage(exception.getMessage());
      // }

      @Override
      protected void onSuccess(String result) {
        String violdation = StringDeserializer.get().deserialize(result);
        if (violdation == null) {
          // valid
          errorReporter.reportErrorMessage(null);
        } else if (violdation.isEmpty()) {
          // invalid but without message specified
          if (message == null) {
            throw new IllegalArgumentException("There is no message for this error.");
          }
          errorReporter.reportErrorMessage(message);
        } else {
          // invalid with the result message
          errorReporter.reportErrorMessage(violdation);
        }
      }
    });
  }

}